public class Solution556 {
    public int nextGreaterElement(int n) {
        StringBuilder stringBuilder=new StringBuilder(String.valueOf(n));
        int target=-1;
        for (int i=stringBuilder.length()-2;i>=0;i--){
            if (stringBuilder.charAt(i)<stringBuilder.charAt(i+1)){
                target=i;
                break;
            }
        }
        if (target==-1){
            return -1;
        }
        int t=target;
        while (t+1<stringBuilder.length() && stringBuilder.charAt(target)<stringBuilder.charAt(t+1)){
            t++;
        }
        char ch=stringBuilder.charAt(t);
        stringBuilder.setCharAt(t,stringBuilder.charAt(target));
        stringBuilder.setCharAt(target,ch);
        for (int i=target+1,j=stringBuilder.length()-1;i<j;i++,j--){
            char c=stringBuilder.charAt(i);
            stringBuilder.setCharAt(i,stringBuilder.charAt(j));
            stringBuilder.setCharAt(j,c);
        }
        long m=Long.parseLong(stringBuilder.toString());
        if (m>Integer.MAX_VALUE){
            return -1;
        }
        return (int)m;
    }

    public static void main(String[] args) {
        System.out.println(new Solution556().nextGreaterElement(12));
    }
}
